#!/bin/bash

. /usr/share/debconf/confmodule
. /usr/share/mysql/mysql-helpers

MYSQLDATA=$(my_print_defaults server mysqld | grep '^--datadir=' | sed -n 's/--datadir=//p' | tail -n 1)
if [ -z "$MYSQLDATA" ];
then
    MYSQLDATA=/var/lib/mysql
fi
MYSQLFILES=/var/lib/mysql-files

take_upstart_job_backup () {
	if [ -e "/etc/init/mysql.conf" ] && [ -d "$MYSQLDATA" ];
	then
		mv /etc/init/mysql.conf $MYSQLDATA/.mysql.conf.backup
	fi
}

invoke() {
	if pathfind invoke-rc.d; then
		invoke-rc.d mysql
	else
		/etc/init.d/mysql $1
	fi
}

check_exit_status() {
        errcode=$1
        if [ $errcode -gt 0 ];
        then
                exit $errcode
        fi
}

MY_BASEDIR_VERSION=$(my_print_defaults --loose-verbose mysqld server | grep basedir | awk -F'=' '{print $2}')
TOKUDB=$(dpkg -l | grep -c 'percona-server-tokudb')
if [ $TOKUDB = 1 ]
then
  path=$(dpkg-query -L `dpkg -l | grep libjemalloc | awk '{print $2}'` | grep libjemalloc.so.1)
  if [ ! -z $path ]
  then
    dir=$(dirname $(readlink -f $path))
    for dir in "${MY_BASEDIR_VERSION}/lib/mysql" "/usr/lib64" "/usr/lib/x86_64-linux-gnu" "/usr/lib"; do
      if [ -r "$dir/libjemalloc.so.1" ]; then
        preload_value=$(grep "LD_PRELOAD" /etc/default/mysql | awk -F'=' '{print $2}')
        if [ "x$preload_value" = "x0" ]; then
            sed -i 's/^LD_PRELOAD.*//' /etc/default/mysql
        fi
        preload_exists=$(grep -c "LD_PRELOAD" /etc/default/mysql)
        thp_exists=$(grep -c "THP_SETTING" /etc/default/mysql)
        if [ $preload_exists = 0 ]
        then
            echo "LD_PRELOAD=$dir/libjemalloc.so.1" >> /etc/default/mysql
        fi
        if [ $thp_exists = 0 ]
        then
            echo "THP_SETTING=never" >> /etc/default/mysql
        fi
        break
      fi
    done
  fi
fi

case "$1" in
	configure)

	if [ -z "$2" ];
	then
		set -e
		# Check if we should override new default auth plugin
		OVERRIDEFILE="/etc/mysql/mysql.conf.d/default-auth-override.cnf"
		if [ ! -d /etc/mysql/mysql.conf.d ]; then
			install -d /etc/mysql/mysql.conf.d
		fi
		if [ ! -e "$OVERRIDEFILE" ];
		then
			db_input high percona-server-server/default-auth-override || true
			db_go
			db_get percona-server-server/default-auth-override && OVERRIDE=${RET}
			if [ "$OVERRIDE" = "Use Legacy Authentication Method (Retain MySQL 5.x Compatibility)" ]; then
				if [ "$RET" = "Use Legacy Authentication Method (Retain MySQL 5.x Compatibility)" ]; then
					install -m 0644 /dev/null "$OVERRIDEFILE"
					echo "# This file is automatically generated by MySQL Maintainer Scripts" >> "$OVERRIDEFILE"
					echo "[mysqld]" >> "$OVERRIDEFILE"
					echo "default-authentication-plugin = mysql_native_password" >> "$OVERRIDEFILE"
				fi
            fi
		fi

		# Check if we should enable lowercase table names
		OVERRIDEFILE="/etc/mysql/mysql.conf.d/lowercase-table-names.cnf"
		if [ ! -e "$OVERRIDEFILE" ];
		then
			db_get percona-server-server/lowercase-table-names && OVERRIDE=${RET}
			if [ "$OVERRIDE" = "Enabled" ]; then
				install -m0644 /dev/null "$OVERRIDEFILE"
				echo "# This file is automatically generated by MySQL Maintainer Scripts" >> "$OVERRIDEFILE"
				echo "[mysqld]" >> "$OVERRIDEFILE"
				echo "lower-case-table-names = 1" >> "$OVERRIDEFILE"
			fi
		fi

                CNF_ACTION="Use NEW my.cnf"
		# If the existing config file is a proper file, we back it up
		if [ -f "/etc/mysql/my.cnf" ] && [ ! -L "/etc/mysql/my.cnf" ]; then
			cp /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
			db_input high percona-server-server/existing_config_file || true
			db_go
			db_get percona-server-server/existing_config_file && CNF_ACTION=${RET}
		fi
		if [ -d /etc/mysql/percona-server.conf.d ]; then
			CONF_EXISTS=$(grep "percona-server.conf.d" /etc/mysql/mysql.cnf | wc -l)
			if [ ${CONF_EXISTS} = 0 ]; then
				echo "!includedir /etc/mysql/percona-server.conf.d/" >> /etc/mysql/mysql.cnf
			fi
		fi
                if [ "${CNF_ACTION}" = "Use NEW my.cnf" ]; then
		        update-alternatives --force --install /etc/mysql/my.cnf my.cnf "/etc/mysql/mysql.cnf" 200
                fi
		if [ ! "$(ls -A ${MYSQLDATA})" ] && [ -d ${MYSQLFILES} ];
		then
			db_get percona-server-server/root-pass && PASSWD=${RET}
			if [ ! -z "${PASSWD}" ];
			then
				SQL=/var/lib/mysql-files/SQL
				install /dev/null -m0600 -omysql -gmysql "${SQL}"

				db_set percona-server-server/root-pass ""
				db_set percona-server-server/re-root-pass ""
				cat << EOF > ${SQL}
USE mysql;
ALTER user 'root'@'localhost' IDENTIFIED BY '${PASSWD}';
SHUTDOWN;
EOF
				PASSWD=""
			else
				SQL=/var/lib/mysql-files/SQL
				cat << EOF > ${SQL}
USE mysql;
INSTALL PLUGIN auth_socket SONAME 'auth_socket.so';
ALTER USER 'root'@'localhost' IDENTIFIED WITH 'auth_socket';
SHUTDOWN;
EOF
			fi
			mysqld --initialize-insecure --user=mysql > /dev/null
			run_init_sql "$SQL"
			rm -f "$SQL"
		fi
		set +e

	fi

	;;

	abort-upgrade|abort-remove|abort-configure)

	;;

	*)
	exit 1
	;;
esac

db_stop

take_upstart_job_backup

#Some postinstall info about UDF
#
echo -e "\n\n * Percona Server is distributed with several useful UDF (User Defined Function) from Percona Toolkit."
echo -e " * Run the following commands to create these functions:\n"
echo -e "\tmysql -e \"CREATE FUNCTION fnv1a_64 RETURNS INTEGER SONAME 'libfnv1a_udf.so'\""
echo -e "\tmysql -e \"CREATE FUNCTION fnv_64 RETURNS INTEGER SONAME 'libfnv_udf.so'\""
echo -e "\tmysql -e \"CREATE FUNCTION murmur_hash RETURNS INTEGER SONAME 'libmurmur_udf.so'\""
echo -e "\n * See http://www.percona.com/doc/percona-server/8.0/management/udf_percona_toolkit.html for more details\n\n"
#

#DEBHELPER#

exit 0
